#!/usr/bin/env python
# -*- coding:utf-8 -*-

from tornado.web import RequestHandler
from tornado import gen
from engine import (BaseHandler, ErrorMessage)
from inke_replace_ads_manager import inkeReplaceAdsManager
#from live_util.common.common import Common
#from live_util.common.transport import Transport
from dm_py_util import (DEBUG_LOG, WARN_LOG, ERROR_LOG,
                        SET_LOG_KEY, BUSINESS_LOG)
import json
import time


class inkeReplaceAdsHandler(RequestHandler):
    interface_name = 'live.user.adscheck'

    def post(self):
        SET_LOG_KEY(self.interface_name)
        start_time = time.time()
        try:
            ret = self.process()
        except Exception as e:
            ERROR_LOG('user process error', e)
            ret = '{"dm_error":500,"error_msg":"内部系统错误"}'
        DEBUG_LOG('response', ret)
        self.finish(ret)
        BUSINESS_LOG('%s|%f|%r|%r' % (self.interface_name, (time.time(
        ) - start_time) * 1000, self.request.query, self.request.body))

    def process(self):
        #TODO: 此处添加业务逻辑
        try:
            post = json.loads(self.request.body)
        except Exception as e:
            ERROR_LOG('parse body error', e)
        DEBUG_LOG('post', post)
        check_word = {}
        for key in post.keys():
            if key == 'nick' or key == 'description':
                check_word[key] = post[key]
        DEBUG_LOG('post finish')
        results = False
        for key in check_word.keys():
            if len(check_word[key].strip()) == 0:
                continue
            if not inkeReplaceAdsManager().check(key, check_word[key]):
                results = False
            else:
                results = True
        DEBUG_LOG('post finish2')
        ret = {'dm_error': 0, 'error_msg': '操作成功', 'check': results}

        DEBUG_LOG('params', self.request.query, self.request.body)
        try:
            ret_str = json.dumps(ret)
        except Exception as e:
            ERROR_LOG('dumps res failed', e)
        return ret_str


class inkeReplaceAdsHandler1(RequestHandler):
    interface_name = 'live.user.adsreplace'

    def post(self):
        SET_LOG_KEY(self.interface_name)
        start_time = time.time()
        try:
            ret = self.process()
        except Exception as e:
            ERROR_LOG('user process error', e)
            ret = '{"dm_error":500,"error_msg":"内部系统错误"}'
        DEBUG_LOG('response', ret)
        self.finish(ret)
        BUSINESS_LOG('%s|%f|%r|%r' % (self.interface_name, (time.time(
        ) - start_time) * 1000, self.request.query, self.request.body))

    def process(self):
        #TODO: 此处添加业务逻辑
        try:
            post = json.loads(self.request.body)
        except Exception as e:
            ERROR_LOG('parse body error', e)
            raise
        check_word = {}
        for key in post.keys():
            if key == 'nick' or key == 'description':
                check_word[key] = post[key]
        for key in check_word.keys():
            if len(check_word[key].strip()) == 0:
                continue
            post[key] = inkeReplaceAdsManager().replace(key, check_word[key])
        DEBUG_LOG('params', self.request.query, self.request.body)
        try:
            ret_str = json.dumps(post)
        except Exception as e:
            ERROR_LOG('dumps res failed', e)
            raise
        return ret_str


class CheckRepeatMessageHandler(BaseHandler):

    @gen.coroutine
    def process(self):

        SET_LOG_KEY('CheckRepeatMesaageHandler')
        resp = {}

        try:
            body = json.loads(self.request.body)
            send_id = int(body['send_id'])
            recv_id = int(body['recv_id'])
            msg = body['msg']
        except Exception as e:
            ERROR_LOG('parse body error', e)
            raise gen.Return(ErrorMessage.CLIENT_ERRROR)
        DEBUG_LOG('get all args send_id=%s, recv_id=%s, msg=%s' %
                  (send_id, recv_id, msg))
        res = inkeReplaceAdsManager().check_repeat_message(send_id, recv_id, msg)
        DEBUG_LOG('check_repeat_message res', res)
        resp['res'] = res
        resp.update(ErrorMessage.SUCCESS)
        raise gen.Return(resp)


class inkeContentAdsHandler(RequestHandler):
    interface_name = 'live.user.contentcheck'

    def post(self):
        SET_LOG_KEY(self.interface_name)
        start_time = time.time()
        try:
            ret = self.process()
        except Exception as e:
            ERROR_LOG('user process error', e)
            ret = '{"dm_error":500,"error_msg":"内部系统错误"}'
        DEBUG_LOG('response', ret)
        self.finish(ret)
        BUSINESS_LOG('%s|%f|%r|%r' % (self.interface_name, (time.time(
        ) - start_time) * 1000, self.request.query, self.request.body))

    def process(self):
        #TODO: 此处添加业务逻辑
        try:
            post = json.loads(self.request.body)
        except Exception as e:
            ERROR_LOG('parse body error', e)
        DEBUG_LOG('post', post)
        # send_id = int(post['send_id'])
        check_word = {}
        for key in post.keys():
            if key == 'content':
                check_word[key] = post[key]
        DEBUG_LOG('post finish')
        results = False
        for key in check_word.keys():
            if len(check_word[key].strip()) == 0:
                continue
            if len(check_word[key].strip()) > 10:
                if not inkeReplaceAdsManager().check_repeat_content(check_word[key]):
                    results = False
                else:
                    results = True
                    break
            if not inkeReplaceAdsManager().checkcontent(key, check_word[key]):
                results = False
            else:
                results = True
                break
            if not inkeReplaceAdsManager().check_Sensitiveword_combination(key, check_word[key]):
                results = False
            else:
                results = True
                break
        DEBUG_LOG('post finish2')
        ret = {'dm_error': 0, 'error_msg': '操作成功', 'check': results}

        DEBUG_LOG('params', self.request.query, self.request.body)
        try:
            ret_str = json.dumps(ret)
        except Exception as e:
            ERROR_LOG('dumps res failed', e)

        return ret_str


if __name__ == '__main__':

    import tornado.web
    import tornado.ioloop
    import tornado.httpserver

    manager = inkeReplaceAdsManager()
    manager.init('/a8root/conf/inke_replace_ads/ads_manager.ini')

    app = tornado.web.Application([(r'/user/adscheck',
                                    inkeReplaceAdsHandler),
                                   (r'/user/adsreplace',
                                    inkeReplaceAdsHandler1),
                                   (r'/user/adsmessagecheck',
                                       CheckRepeatMessageHandler),
                                   (r'/user/adscontentcheck',
                                    inkeContentAdsHandler)])

    server = tornado.httpserver.HTTPServer(app)
    server.listen(8786)
    tornado.ioloop.IOLoop.current().start()
